package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.mail.MessagingException;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.BannedUserCache;
import com.conversationboard.captcha.CaptchaService;
import com.conversationboard.config.Configuration;
import com.conversationboard.email.Mail;
import com.conversationboard.model.User;
import com.octo.captcha.service.CaptchaServiceException;

@WebServlet(name = "WebMailControllerServlet", urlPatterns = "/WebMailControllerServlet")
public class WebMailControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 5445105212030982036L;


	/**
	 * Collect the message ID, translate it into the user's email address and
	 * send the email.
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String boardId = (String) request.getParameter("boardid");
		String threadId = (String) request.getParameter("threadid");
		String messageId = (String) request.getParameter("messageid");
		String messageBody = (String) request.getParameter("text");

		int boardIdNumber = Integer.parseInt(boardId);
		int threadIdNumber = Integer.parseInt(threadId);
		int messageIdNumber = Integer.parseInt(messageId);

		try {

			String senderId = request.getUserPrincipal().getName();
			User senderUser = User.get(senderId);

			String sender = senderUser.getDisplayName();

			/* Don't allow banned users to send webmails */

			if (BannedUserCache.isBanned(-1, false, senderUser.getLoginId())) {
				return;
			}

			/* Ensure the user has passed the CAPTCHA test correctly */

			if (Configuration.getInstance().isCaptchaEnabled()) {

				String captchaId = request.getSession().getId();
				String userTypedIn = request.getParameter("captcha");

				boolean validated = CaptchaService.getInstance().validateResponseForID(captchaId, userTypedIn);

				if (!validated) {
					RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
					request.setAttribute("message", "You did not type in the correct letters as shown in the image.");
					dispatcher.forward(request, response);
					return;
				}
			}

			/* Get the email address from the message ID */

			String loginId = User.getLoginIdFromMessageId(boardIdNumber, threadIdNumber, messageIdNumber);

			Mail mail = new Mail();
			mail.send(senderId, loginId, "Email from user: " + sender, messageBody);

			String message = "Your email has been successfully sent.";
			request.setAttribute("message", message);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");

			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (NamingException e) {
			throw new ServletException(e);
		} catch (MessagingException e) {
			throw new ServletException(e);
		} catch (CaptchaServiceException e) {
			/* Swallow */
		}

	}

}
